<template>
  <Form ref="formValidate" :model="formValidate" :rules="ruleValidate"
        :label-width="120" style="">

    <FormItem label="推荐规则名称" prop="name">
      <Input v-model="formValidate.name" placeholder="请输入推荐规则名称" style="width: 200px;"></Input>
    </FormItem>
    <FormItem label="推荐渠道" prop="channel">
      <Select v-model="formValidate.channel" placeholder="请选择渠道"  style="width: 200px;">
        <Option v-for="(item,index) in channelList" :value="item.channelId">{{item.channelName}}</Option>
      </Select>
    </FormItem>
    <FormItem label="推荐规则描述" prop="desc">
      <Input v-model="formValidate.desc" type="textarea" :autosize="{minRows: 2,maxRows: 5}"
             style="width: 200px;"    placeholder="请输入推荐规则描述"></Input>
    </FormItem>

    <p class="division">
      <Icon type="person-stalker"
         style="color: #6d1786;font-size: 18px;margin-right: 10px;"></Icon>客群属性</p>
    <FormItem label="选择客群" prop="guestGroup">
      <Select v-model="formValidate.guestGroup" @on-change="guestChange"
              placeholder="从已有客群选择"  style="width: 200px;">
        <Option v-for="(item,index) in guestList" :value="item.id">{{item.cgName}}</Option>
      </Select>

      <Button type="ghost" @click="addGuest"
              style="margin-left: 10px;">新建筛选客群</Button>
    </FormItem>
    <div v-if="newGuest" style="background:#f8f8f8;padding:15px 0;">

      <FormItem label="筛选条件" prop="conditions">
        <div>
          <p style="margin-bottom: 10px;" v-for="(unit,index) in selectedLabel">
            <Tag :id="unit.dimNo">{{unit.dimNm}}</Tag>
            <Select v-model="unit.type" :disabled="unit.isMulti=='1'?true:false"
                    @on-change="containListChange(unit.type,index)" style="width:100px;display: inline-block">
              <Option v-for="item in containList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
            <Select v-model="unit.valueList" :multiple="(unit.type=='contain')?true:false"  style="width:160px;margin-left: 5px;display: inline-block">
              <Option v-for="item in unit.resultList" :value="item.labelItemNo" :key="item.labelItemNo">{{ item.labelItemName }}</Option>
            </Select>
          </p>
        </div>
        <Select v-model="formValidate.conditions" filterable multiple label-in-value @on-change='selectLabel'
                placeholder="请输入关键词搜索" style="width: 200px;">
          <Option v-for="item in labelList" :value="item.dimNo" :key="item.dimNo">{{ item.dimNm }}</Option>
        </Select>
      </FormItem>

      <FormItem label="" prop="satisfy">
        <Select v-model="formValidate.filterType" style="display: inline-block;width: 150px;">
          <Option value="and">满足所有条件</Option>
          <Option value="or">满足任意条件</Option>
        </Select>
      </FormItem>

      <p style="text-align: center;">
        <Button type="primary" @click="addGuestGroup = true">保存客群</Button>
      </p>

      <Modal
        v-model="addGuestGroup"
        title="保存客群">
        <!--@on-ok="ok"-->
        <!--@on-cancel="cancel">-->
        <Form ref="guestGroup" :model="guestGroup"
        :label-width="100">
          <FormItem label="客群名称" prop="name">
            <Input v-model="guestGroup.name" placeholder="请输入客群名称" style="width: 200px;"></Input>
          </FormItem>

          <FormItem label="客群描述" prop="desc">
            <Input v-model="guestGroup.desc" type="textarea" :autosize="{minRows: 2,maxRows: 5}"
                   style="width: 200px;"    placeholder="请输入客群描述"></Input>
          </FormItem>

          <FormItem label="客群分类" prop="channel">
            <Select v-model="guestGroup.guestType" placeholder="请选择客群分类"  style="width: 200px;">
              <Option value="01">理财客群</Option>
            </Select>
          </FormItem>
          <FormItem style="margin-bottom: 0;text-align: left;margin-top: 20px;">
            <Button type="primary" @click="saveGuest" style="margin-right: 40px;">保存</Button>
            <Button type="ghost" @click="resetGuest" style="margin-left: 8px">取消</Button>
          </FormItem>
        </Form>
        <div slot="footer">

        </div>
      </Modal>

    </div>



    <p class="division" style="margin-top: 10px;">
      <Icon type="bag"
            style="color: #6d1786;font-size: 18px;margin-right: 10px;"></Icon>产品属性</p>


    <FormItem label="产品类型" prop="productType" >
      <Select v-model="formValidate.productType" @on-change="productTypeChange"
              placeholder="请选择产品类型" style="width: 200px;">
        <Option v-for="item in productTypeList" :value="item.proTypeId" :key="item.proTypeId">{{ item.proTypeName }}</Option>

      </Select>
    </FormItem>

    <FormItem label="产品组选择" prop="productGroup">
      <Select v-model="formValidate.productGroup" @on-change="productChange"
              placeholder="从已有产品组选择"  style="width: 200px;">
        <Option v-for="(item,index) in productList" :value="item.id">{{item.pgName}}</Option>
      </Select>

      <Button type="ghost" @click="addProduct"
              style="margin-left: 10px;">新建产品组</Button>
    </FormItem>
    <div v-if="newProduct" style="background:#f8f8f8;padding:15px 0;">

      <FormItem label="筛选条件" prop="conditions2">
        <div>
          <p style="margin-bottom: 10px;" v-for="(unit,index) in selectedOptions">
            <Tag :id="unit.dimNo">{{unit.dimNm}}</Tag>
            <Select v-model="unit.type" @on-change="containListChange2(unit.type,index)" style="width:100px;display: inline-block">
              <Option v-for="item in containList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
            <Select v-model="unit.valueList" :multiple="(unit.type=='contain')?true:false"  style="width:160px;margin-left: 5px;display: inline-block">
              <Option v-for="item in unit.resultList" :value="item.itemNo" :key="item.itemNo">{{ item.itemName }}</Option>
            </Select>
          </p>
        </div>
        <Select v-model="formValidate.conditions2" filterable multiple label-in-value @on-change='selectOption'
                placeholder="请输入关键词搜索" style="width: 200px;">
          <Option v-for="item in optionList" :value="item.attrId" :key="item.attrId">{{ item.attrName }}</Option>
        </Select>
      </FormItem>

      <FormItem label="" prop="satisfy">
        <Select v-model="formValidate.filterType2" style="display: inline-block;width: 150px;">
          <Option value="and">满足所有条件</Option>
          <Option value="or">满足任意条件</Option>
        </Select>
      </FormItem>

      <p style="text-align: center;">
        <Button type="primary" @click="addProductGroup = true">保存产品组</Button>
      </p>

      <Modal
        v-model="addProductGroup"
        title="保存产品组">
        <!--@on-ok="ok"-->
        <!--@on-cancel="cancel">-->
        <Form ref="productGroup" :model="productGroup"
              :label-width="100">
          <FormItem label="产品组名称" prop="name">
            <Input v-model="productGroup.name" placeholder="请输入产品组名称" style="width: 200px;"></Input>
          </FormItem>

          <FormItem label="产品组描述" prop="desc">
            <Input v-model="productGroup.desc" type="textarea" :autosize="{minRows: 2,maxRows: 5}"
                   style="width: 200px;"    placeholder="请输入产品组描述"></Input>
          </FormItem>

          <FormItem label="产品组分类" prop="channel">
            <Select v-model="productGroup.proType"
                    placeholder="请选择产品组分类"  style="width: 200px;">
              <Option v-for="item in productTypeList" :value="item.proTypeId" :key="item.proTypeId">{{ item.proTypeName }}</Option>
            </Select>
          </FormItem>
          <FormItem style="margin-bottom: 0;text-align: left;margin-top: 20px;">
            <Button type="primary" @click="saveProduct" style="margin-right: 40px;">保存</Button>
            <Button type="ghost" @click="resetProduct" style="margin-left: 8px">取消</Button>
          </FormItem>
        </Form>
        <div slot="footer">

        </div>
      </Modal>

    </div>


    <FormItem style="margin-bottom: 0;text-align: left;margin-top: 20px;">
      <Button type="primary" @click="handleSubmit('formValidate')" style="margin-right: 40px;">保存</Button>
      <Button type="ghost" @click="resetAll" style="margin-left: 8px">重置</Button>
    </FormItem>
  </Form>
</template>

<script>

  import Regular from '../../utils/regular'
  import {PROTYPES} from '../../utils/common'

  export default{
    data: function () {
      return {
        isEdit:false,

        addGuestGroup: false,
        addProductGroup: false,

        newGuest:false,
        newProduct:false,

        selectedLabel:[],
        selectedOptions:[],
        containList:[
          {label:'等于',value:'equal'},
          {label:'包含',value:'contain'}
        ],

        labelList:[],
        optionList:[],

        channelList:'',
        guestList:'',
        productList:'',
        productTypeList:PROTYPES,

        guestGroup:{
          name:'',
          desc:'',
          guestType:''
        },
        productGroup:{
          name:'',
          desc:'',
          proType:''
        },
        formValidate: {
        name: '',
        channel:'',
        desc: '',
          guestGroup:'',

          productType:"01",
          productGroup:'',

          conditions:'',
          filterType:'and',

          conditions2:'',
          filterType2:'and'
      },
        ruleValidate: {
          name: [
            { required: true, message: '请输入推荐规则名称', trigger: 'blur' }
          ],
          channel: [
            { required: true, message: '请选择推荐渠道', trigger: 'change' }
          ],
          desc: [
            { required: true, message: '请输入推荐规则描述', trigger: 'blur' },
            { type: 'string', min: 3, message: '不能少于3个字符', trigger: 'blur' }
          ]
        }
      }
    },
    components: {},
    methods: {
      getDetails(data){
        this.isEdit = true
        let _this = this

        this.formValidate.name = data.reguName
        this.formValidate.channel = data.channelId
        this.formValidate.desc = data.reguDesc
        this.formValidate.id = data.regulationId
        this.formValidate.cgId = data.cgId
        this.formValidate.pgId = data.pgId

        let cgId = data.cgId
        let pgId = data.pgId

        let cgLabels,pgLabels,cgMark,pgMark;

        //获取客群信息
        this.api({
          url: "/customer/group/detail",
          method: "post",
          params:{
            id:cgId
          }
        }).then(data => {
          cgLabels = data.labels;
          cgMark = data.saveMark;
          if(cgMark == '1'){
            _this.formValidate.guestGroup = data.id
            _this.newGuest = false
          }else {
            _this.newGuest = true
            _this.formValidate.filterType = Regular.toJson(data.labels).filterType
            _this.filters = Regular.toJson(data.labels).filters
            // console.log(_this.filters)
            let tempCondition=[]
            _this.filters.forEach(function (item,index) {
              tempCondition.push(item.fieldNo)
            })
            this.formValidate.conditions = tempCondition

          }
        })
        //获取产品组信息
        this.api({
          url: "/product/group/detail",
          method: "post",
          params:{
            id:pgId
          }
        }).then(data => {
          pgLabels = data.labels;
          pgMark = data.saveMark;
          _this.formValidate.productType = data.proType||'01'

          if(pgMark == '1'){
            //产品组列表
            this.getProductGroupList(()=>{
              _this.formValidate.productGroup = data.id
            })

            _this.newProduct = false
          }else {
            _this.newProduct = true
            _this.formValidate.filterType2 = Regular.toJson(data.labels).filterType
            _this.filters2 = Regular.toJson(data.labels).filters
            // console.log(_this.filters2)
            let tempCondition=[]
            _this.filters2.forEach(function (item,index) {
              tempCondition.push(item.fieldNo)
            })
            this.formValidate.conditions2 = tempCondition

          }
        })
      },
      handleSubmit (name) {
        let _this = this;
        let forceStop = false
        this.$refs[name].validate((valid) => {
          if (valid) {
            let guestConditions = []
            let guestType = this.formValidate.filterType
            let productConditions = []
            let productType = this.formValidate.filterType2

            this.selectedLabel.forEach(function (item) {
              let temp = {};
              temp.fieldNo = item.dimNo
              temp.valueList = item.valueList
              temp.type = item.type
              //temp.valuetype = (item.valueList.length>1)?1:0
              if(item.valueList=='' || item.valueList==[] || !item.valueList){
                _this.$Message.error('标签属性值不能为空!');
                forceStop = true
                return;
              }
              // console.log(item)
              guestConditions.push(temp)
            })
            // console.log(guestConditions)
            this.selectedOptions.forEach(function (item) {
              let temp = {};
              temp.fieldNo = item.dimNo
              temp.valueList = item.valueList
              temp.type = item.type
              temp.valuetype = (item.valueList.length>1)?1:0

              if(item.valueList=='' || item.valueList==[] || !item.valueList){
                _this.$Message.error('产品属性值不能为空!');
                forceStop = true
                return;
              }
              productConditions.push(temp)
            })

            if(forceStop){
              return;
            }

           let customLabel = Regular.toRegular({"filterType": guestType},{"filters": guestConditions})
           let productLabel = Regular.toRegular({"filterType": productType},{"filters": productConditions})

            if(this.isEdit){
              this.api({
                url: "/regulation/update",
                method: "post",
                params:{
                  regulationId:this.formValidate.id,
                  reguName:this.formValidate.name,
                  reguDesc:this.formValidate.desc,
                  channelId:this.formValidate.channel,
                  cgId:this.formValidate.cgId,
                  pgId:this.formValidate.pgId,
                  proType:this.formValidate.productType,
                  customLabel:customLabel,
                  productLabel:productLabel
                }
              }).then(data => {
                this.$Message.success('修改推荐规则成功!');
                _this.$parent.cancel()
                _this.isEdit = false
                _this.resetAll()
                _this.$emit('refreshbizlines')
              })
            }else {
              this.api({
                url: "/regulation/add",
                method: "post",
                params:{
                  reguName:this.formValidate.name,
                  reguDesc:this.formValidate.desc,
                  channelId:this.formValidate.channel,
                  cgId:this.formValidate.guestGroup,
                  pgId:this.formValidate.productGroup,
                  proType:this.formValidate.productType,
                  customLabel:customLabel,
                  productLabel:productLabel
                }
              }).then(data => {
                this.$Message.success('新增推荐规则成功!');
                _this.$parent.cancel()
                _this.isEdit = false
                _this.resetAll()
                _this.$emit('refreshbizlines')
              })
            }

          } else {
            //this.$Message.error('Fail!');
          }
        })
      },
      handleReset (name) {
        this.$refs[name].resetFields();
      },
      reset(){
        this.$refs['formValidate'].resetFields();
      },
      resetAll(){
        this.isEdit = false

        this.addGuestGroup = false
        this.addProductGroup = false
        this.newGuest = false
        this.newProduct = false

        this.selectedLabel=[]
        this.selectedOptions=[]

        this.$refs['formValidate'].resetFields();
        this.formValidate.conditions = [];
        this.formValidate.conditions2 = [];
        if(this.$refs['guestGroup']) this.$refs['guestGroup'].resetFields();
        if(this.$refs['productGroup']) this.$refs['productGroup'].resetFields();

      },
      productTypeChange(val){
        this.formValidate.productGroup = ''
        this.api({
          url: "/product/group/list",
          method: "post",
          params:{
            type:val
          }
        }).then(data => {
          this.productList = data;
        })
      },
      guestChange(val){
        if(val) this.newGuest = false
      },
      addGuest(){
        this.newGuest = true;
        this.formValidate.guestGroup = '';
      },
      saveGuest(){
        let _this = this
        this.$refs['guestGroup'].validate((valid) => {
          if (valid) {
            let guestConditions = []
            let guestType = this.formValidate.filterType
            this.selectedLabel.forEach(function (item) {
              let temp = {};
              temp.fieldNo = item.dimNo
              temp.valueList = item.valueList
              temp.type = item.type
              //temp.valuetype = item.isMulti
              guestConditions.push(temp)
            })
            let customLabel = Regular.toRegular({"filterType": guestType},{"filters": guestConditions})

            if(_this.formValidate.cgId && _this.isEdit){
              _this.api({
                url: "/customer/group/update",
                method: "post",
                params:{
                  id:_this.formValidate.cgId,
                  labels:customLabel,
                  cgName:this.guestGroup.name,
                  cgDesc:this.guestGroup.desc,
                  cgType:this.guestGroup.guestType
                }
              }).then(data => {
                this.$Message.success('保存客群成功!');
                _this.addGuestGroup = false
                _this.getGuestGroupList()
              })
            }else {
              _this.api({
                url: "/customer/group/add",
                method: "post",
                params:{
                  labels:customLabel,
                  cgName:this.guestGroup.name,
                  cgDesc:this.guestGroup.desc,
                  cgType:this.guestGroup.guestType
                }
              }).then(data => {
                this.$Message.success('保存客群成功!');
                _this.addGuestGroup = false
                _this.getGuestGroupList()
              })
            }

          } else {
            //this.$Message.error('Fail!');
          }
        })
      },
      resetGuest(){
        this.addGuestGroup = false
      },
      selectLabel(val){
        Regular.makeUp(val,this.selectedLabel,'/label/item/list',this.isEdit,this.filters,false,this.labelList)
      },

      productChange(val){
        if(val) this.newProduct = false
      },
      addProduct(){
        this.newProduct = true
        this.formValidate.productGroup = ''
      },
      saveProduct(){
        let _this = this
        this.$refs['productGroup'].validate((valid) => {
          if (valid) {
            let productConditions = []
            let productType = this.formValidate.filterType2

            this.selectedOptions.forEach(function (item) {
              let temp = {};
              temp.fieldNo = item.dimNo
              temp.valueList = item.valueList
              temp.type = item.type
              //temp.valuetype = item.isMulti
              productConditions.push(temp)
            })

            let customLabel = Regular.toRegular({"filterType": productType},{"filters": productConditions})

            if(_this.formValidate.pgId && _this.isEdit){
              _this.api({
                url: "/product/group/update",
                method: "post",
                params:{
                  id:_this.formValidate.pgId,
                  labels:customLabel,
                  pgName:this.productGroup.name,
                  pgDesc:this.productGroup.desc,
                  proType:this.productGroup.proType
                }
              }).then(data => {
                this.$Message.success('保存产品组成功!');
                _this.addProductGroup = false
                _this.getProductGroupList()
              })
            }else{
              _this.api({
                url: "/product/group/add",
                method: "post",
                params:{
                  labels:customLabel,
                  pgName:this.productGroup.name,
                  pgDesc:this.productGroup.desc,
                  proType:this.productGroup.proType
                }
              }).then(data => {
                this.$Message.success('保存产品组成功!');
                _this.addProductGroup = false
                _this.getProductGroupList()
              })
            }

          } else {
            //this.$Message.error('Fail!');
          }
        })
      },
      resetProduct(){
        this.addProductGroup = false
      },
      selectOption(val){
        // console.log(this.filters2)
        Regular.makeUp(val,this.selectedOptions,'/product/attr/item/list',this.isEdit,this.filters2,true)
      },

      getGuestGroupList(cb){
        this.api({
          url: "/customer/group/list ",
          method: "post"
        }).then(data => {
          this.guestList = data;
          cb&&cb()
        })
      },
      getProductGroupList(cb){
        this.api({
          url: "/product/group/list",
          method: "post",
          params:{
            type:this.formValidate.productType
          }
        }).then(data => {
          this.productList = data;
          cb&&cb()
        })
      },
      containListChange(type,index){
        this.selectedLabel[index].valueList =[]
      },
      containListChange2(type,index){
        this.selectedOptions[index].valueList =[]
      }


    },
    created(){
//推荐渠道列表
      this.api({
        url: "/channel/list",
        method: "post"
      }).then(data => {
        this.channelList = data;
      })

      //客群列表
     this.getGuestGroupList()

      //产品组列表
      this.getProductGroupList()

      //标签列表
      this.api({
        url: "/label/list",
        method: "post"
      }).then(data => {
        this.labelList = data;
      })
      //产品属性列表
      this.api({
        url: "/product/attr/list",
        method: "post"
      }).then(data => {
        this.optionList = data;
      })
    },
    mounted() {


    }
  }
</script>

<style lang="scss" scoped>
  .division {
    padding-left: 20px;
    line-height: 24px;
    border-bottom: 1px solid #e9eaec;
    margin-bottom: 20px;
  }
  .division .ivu-icon {
    line-height: 24px;
  }
</style>
